import axios from 'axios';
import { deepCopyObj, copyObjBySelf, deepCopyObjArray } from '../../../assets/js/help.js';
export default {
  data() {
    var validatePrice = (rule, value, callback) => {
      if (value === null || value === '') {
        return callback(new Error('单价不能为空'));
      }
      if (value === 0) {
        return callback();
      }
      if (!/^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/.test(value)) {
        return callback(new Error('请输入正确的金额'));
      } else {
        if (value < 0) {
          return callback(new Error('单价不能小于0'));
        } else {
          callback();
        }
      }
    };
    var validateSellFromTo = (rule, value, callback) => {
      if (value == null || value == '' || value == ',') {
        return callback(new Error('请选择可销售时间'));
      }
      callback();
    };
    var validateValidFromTo = (rule, value, callback) => {
      if (this.mouthTicketData.ticketModalName == '创建对外月票') {
        if (value == null || value == '' || value == ',') {
          return callback(new Error('请选择有效期'));
        }
      }
      callback();
    };
    var validateParkJson = (rule, value, callback) => {
      var self = this;
      if (!self.tableData.parkItems.length) {
        return callback(new Error('请选择支持的停车场'));
      }
      callback();
    };
    var validateMaxSellNum = (rule, value, callback) => {
      var self = this;
      if (self.mouthTicketData.baseTicketData.maxSellLimit == 'YES') {
        if (value === null || value === '') {
          return callback(new Error('数量不能为空'));
        }
        if (!/^[1-9]+[0-9]*$/.test(value)) {
          return callback(new Error('请输入大于0的数量'));
        }
      }
      callback();
    };
    var validateInviteCarTotal = (rule, value, callback) => {
      if (value === null || value === '') {
        return callback(new Error('数量不能为空'));
      }
      if(value==='0' || value===0){
        callback();
      }
      if (!/^[1-9]+[0-9]*$/.test(value)) {
        return callback(new Error('请输入大于等于0的数量'));
      }
      callback();
    };
    var validateRenewFormerDays = (rule, value, callback) => {
      var self = this;
      if (self.mouthTicketData.baseTicketData.renewFormerDays) {
        if (value === null || value === '') {
          return callback(new Error('数量不能为空'));
        }
        if (!/^[1-9]+[0-9]*$/.test(value)) {
          return callback(new Error('请输入大于等于0的数量'));
        }
      }
      callback();
    };
    var today = [new Date(moment().format('YYYY-MM-DD 00:00:00')), new Date(moment().format('YYYY-MM-DD 23:59:59'))];
    return {
      // 停车场树-全选功能参数-start
      selectParkModalStatus: 0,
      selectAllItemsStatus: 0,
      itemsNum: 0,
      // 停车场树-全选功能参数-end
      itemsKeyName: '', //停车场树-搜索keyword
      supportParkList: [],
      financialParkId: '',
      isShowTree: true, //判断是不是有树的数据  再显示弹框是暂无数据还是显示树
      enableParkSysType: true,
      supportPark: {
        theadsInfo: [
          {
            index: 0,
            isShow: false,
            prop: 'parkName',
            text: '停车场',
            minWidth: 120
          },
          {
            index: 1,
            isShow: false,
            prop: 'parkVipTypeName',
            text: '绑定VIP类型',
            minWidth: 120
          },
          {
            index: 2,
            isShow: false,
            prop: 'isFinancialPark',
            text: '财务主体',
            minWidth: 120
          }
        ]
      },
      synchronismDetialList: [],
      synchronismDetial: {
        theadsInfo: [
          {
            index: 1,
            isShow: false,
            prop: 'parkName',
            text: '停车场',
            minWidth: 180
          },
          {
            index: 2,
            isShow: false,
            prop: 'sendTime',
            text: '同步时间',
            minWidth: 180
          },
          {
            index: 3,
            isShow: false,
            prop: 'sendStatusName',
            text: '同步结果',
            minWidth: 120
          },
          {
            index: 4,
            isShow: false,
            prop: 'respDesc',
            text: '失败原因',
            minWidth: 400
          },
          {
            index: 5,
            isShow: false,
            prop: 'resend',
            text: '操作',
            minWidth: 120
          }
        ]
      },
      //显示以及语音-aa
      showMessage: null,
      showMessage_: {
        validInWarnOut: {
          carIn: {
            easy: {
              id: null,
              text: '%P\\%VM',
              voice: '%P%VM'
            },
            hard: {
              id: null,
              text: '%P\\%VM请稍候',
              voice: '%P%VM请稍候'
            }
          },
          carOut: {
            easy: {
              id: null,
              text: '%P\\%VM',
              voice: '%P%VM'
            },
            hard: {
              id: null,
              text: '%P\\%VM请稍候',
              voice: '%P%VM请稍候'
            }
          }
        },
        validInWarnIn: {
          carIn: {
            easy: {
              id: null,
              text: '%P\\剩余%VT天',
              voice: '%P剩余%VT天'
            },
            hard: {
              id: null,
              text: '%P\\剩余%VT天',
              voice: '%P剩余%VT天'
            }
          },
          carOut: {
            easy: {
              id: null,
              text: '%P\\剩余%VT天',
              voice: '%P剩余%VT天'
            },
            hard: {
              id: null,
              text: '%P\\剩余%VT天',
              voice: '%P剩余%VT天'
            }
          }
        },
        validOutDelIn: {
          carIn: {
            easy: {
              id: null,
              text: '%P\\%VM已过期',
              voice: '%P%VM已过期'
            },
            hard: {
              id: null,
              text: '%P\\%VM已过期',
              voice: '%P%VM已过期'
            }
          },
          carOutPay: {
            easy: {
              id: null,
              text: '%VM已过期\\应缴费%C元',
              voice: '%VM已过期应缴费%C元'
            },
            hard: {
              id: null,
              text: '%VM已过期\\应缴费%C元',
              voice: '%VM已过期应缴费%C元'
            }
          },
          carOutNoPay: {
            easy: {
              id: null,
              text: '%P\\%VM已过期',
              voice: '%P%VM已过期'
            },
            hard: {
              id: null,
              text: '%P\\%VM已过期',
              voice: '%P%VM已过期'
            }
          }
        }
      },
      //高级配置-aaa
      vipTypeData: {
        id: null,
        customVipName: '',
        settlementType: 0,
        settlementAmount: null,
        isDynamicMode: 0,
        dynamicCarportNumber: null,
        isDatePrivilege: 0,
        isTimePrivilege: 0,
        privilegeTimePeriod: null,
        isChargeGroupRelated: 0,
        chargeGroupCode: null,
        vipGroupType: 0,
        dynamicFullLimit: 0,
        dynamicCarNumber: null,
        vipNearExpiredDayThreshold: 10, //到期提醒时长天数
        vipDeleteExpiredDayThreshold: 0, //删除期天数
        openVipFullLimit: 0,
        vipFullLimitValue: '',
        vipFullOpenModel: 0,
        vipRecoverTime: null,
        priTimeArr: today,
        priTimeArrFrom: '', //开始时间
        priTimeArrTo: '', //结束时间
        priDateArrStr: '',
        parkId: '',
        parkName: '',
        channelAuthTree: '',
        channelSeqList: []
      },
      editModelReadonly: false,
      isShowTips: false,
      mouthTicketData: {
        tabName: 'basicTab',
        ticketModalName: '',
        //基础信息
        baseTicketData: {
          id: '',
          parkSysType: '', //停车场类型
          vipGroupType: 2, //特殊车辆类型
          name: '', //类型名称
          description: '', //简介
          sellFromTo: [],
          validFromTo: [],
          validDateType: '',
          maxSellNum: '',
          financialParkId: '', //记录哪一个停车场为财务主体
          parkJson: [], //每条记录都记录 停车场的ID和对应的VIP类型的关系
          remark: '',
          sellingPic: '',
          selloutPic: '',
          sellingPicName: '',
          selloutPicName: '',
          renewFormerDays: 0,
          inviteCarTotal: 3,
          parkVipTypeJson: ''
        }
      },
      picPath: {
        sellingPicPath: '',
        selloutPicPath: ''
      },
      entity: {
        id: null,
        name: '',
        description: '',
        parkList: [],
        vipSeq: '',
        vipName: '',
        maxCarNum: '',
        availableParkCodeList: [],
        sellFromTo: '',
        activeTimeFromTo: '',
        originalPriceMonthly: '',
        realPriceMonthly: '',
        pic: '',
        remark: ''
      },
      tableData: {
        parkItems: [] //通过停车场的ID请求到的停车场对应的VIP类型的列表
      },
      picShow: {
        sellingPicShow: '',
        selloutPicShow: ''
      },
      rules: {
        vipGroupType: [
          {
            required: true,
            message: '请选择特殊车辆类型'
          }
        ],
        name: [
          {
            required: true,
            message: '类型名称不能为空',
            trigger: ['change', 'blur']
          },
          {
            min: 2,
            max: 200,
            message: '长度在 2 到 200 个字符',
            trigger: ['change', 'blur']
          }
        ],
        description: [
          {
            max: 200,
            message: '最多200 个字符',
            trigger: ['change', 'blur']
          }
        ],
        sellFromTo: [
          {
            validator: validateSellFromTo,
            trigger: 'change'
          }
        ],
        validFromTo: [
          {
            required: true,
            message: '请选择有效期'
          },
          {
            validator: validateValidFromTo,
            trigger: 'change'
          }
        ],
        parkJson: [
          {
            validator: validateParkJson,
            trigger: ['change', 'blur']
          }
        ],
        remark: [
          {
            max: 100,
            message: '最多100 个字符',
            trigger: ['change', 'blur']
          }
        ],
        vipFullLimitValue: [
          {
            required: true,
            message: '请填写满位控制数量'
          },
          {
            type: 'number',
            message: '该字段必须为数字值',
            trigger: ['change', 'blur']
          }
        ],
        priTimeArr: [
          {
            required: true,
            message: '请选择时间段'
          }
        ],
        priTimeArrFrom: [
          {
            required: true,
            message: '请选择开始时间'
          }
        ],
        priTimeArrTo: [
          {
            required: true,
            message: '请选择结束时间'
          }
        ]
      },
      modalStatus: '', //模态框状态(1:创建;2:编辑基础信息、3:高级配置、4:显示及语音;5:查看)
      isShowBlock: false,
      selectedParkingLot: '', //已选择的停车场树数据
      selectedParkingLotStr: '', //已选择停车场
      specialCarTypeObj: {
        //查看特殊车辆类型obj
        dialogVisible: false, //查看框是否显示
        tabName: '',
        basicData: {
          channelArr: [], //所选通道
          vipGroupTypeStr: '', //特殊车辆类型
          name: '', //类型名称
          description: '' //简介
        },
        superiorData: {
          moreCarMoreSeat: '', //是否支持多车多位
          autoSwitchVip: '', //是否支持场内切换
          dynamicFullLimit: '', //是否支持内场多位多车满位到剩余

          openVipFullLimit: '', //是否支持满位控制
          vipFullLimitValue: '', //最多可进多少辆车
          vipFullOpenModel: '', //满位放行模式

          isDatePrivilege: '', //是否按日期
          priDateArrStr: '', //已选择的日期

          isTimePrivilege: '', //是否按时间段
          timeSlot: '', //时间段

          iScharging: '' //是否计费
        }
      },
      allParkingTreeData: [], //所有停车场树数据
      parkingTreeDataUrl: '/vip/vipType/getChannelAuthTreeMultiPark.do', //获取停车场树数据接口url
      settings: {
        check: {
          enable: true,
          autoCheckTrigger: true,
          chkboxType: {
            Y: 'ps',
            N: 'ps'
          }
        },
        data: {
          key: {
            checked: 'checked',
            chkDisabled: true,
            children: 'childrenList'
          }
        },
        view: {
          showIcon: false,
          showLine: false
        },
        callback: {
          onCheck: this.setChkDisabledEvent
        }
      },
      dialogVisibleOfShowMessage: false //显示及语音显示框
    };
  },
  watch: {
    'tableData.parkItems': function(newMouthTicketData) {
      if (this.$refs.ticketForm) {
        this.$refs.ticketForm.validateField('parkJson');
      }
    }
  },
  created() {
    this.getAllParkingTreeData();
    this.showMessage = deepCopyObj(this.showMessage_);
  },
  mounted() {
    let _this = this;
    _this.toBase64(_this);
  },
  methods: {
    // 显示及语音-框
    textVoice(rowData) {
      let self = this;
      self.modalStatus = 4;
      let params = {};
      params.id = rowData.id;
      API.operation.GetSpecialCarTypeConfigDetail(params).then(
        res => {
          self.initMouthData_edit(res.data);
          self.dialogVisibleOfShowMessage = true;
        },
        err => {}
      );
    },
    // 停车场树选项是否可以被选择
    setChkDisabledEvent(event, treeId, treeNode) {
      let treeObj = $.fn.zTree.getZTreeObj('ParkTree');
      let isChecked = treeNode.checked; //是否被选择
      let parkSysType = treeNode.parkSysType; //所属车场类型
      let parkingLotTreeNodes = treeObj.getNodes(); //所有的停车场节点
      let selectedNodes = treeObj.getCheckedNodes(true); //选择的节点
      let selectedNodesLength = selectedNodes.length;
      for (let i = 0; i < parkingLotTreeNodes.length; i++) {
        if (parkingLotTreeNodes[i].parkSysType !== parkSysType) {
          if (!isChecked) {
            //取消选择
            if (!selectedNodesLength) {
              //没有节点被选中
              treeObj.setChkDisabled(parkingLotTreeNodes[i], false, true, true);
            } else {
              treeObj.setChkDisabled(parkingLotTreeNodes[i], true, true, true);
            }
          } else {
            treeObj.setChkDisabled(parkingLotTreeNodes[i], true, true, true);
          }
        } else {
          treeObj.setChkDisabled(parkingLotTreeNodes[i], false, true, true);
        }
      }
    },
    // 获取vems停车场树数据
    fetchVemsParkingTreeData() {
      let params = {
        parkId: null,
        vipTypeId: null,
        parkSysType: 0,
        canCheckAll: 1
      };
      return API.fetchPost(this.parkingTreeDataUrl, params);
    },
    // 获取云停车场树数据
    fetchParkingTreeData() {
      let params = {
        parkId: null,
        vipTypeId: null,
        parkSysType: 1,
        canCheckAll: 1
      };
      return API.fetchPost(this.parkingTreeDataUrl, params);
    },
    // 获取所有停车场树数据
    getAllParkingTreeData() {
      let self = this;
      axios.all([self.fetchVemsParkingTreeData(), self.fetchParkingTreeData()]).then(
        axios.spread((vems, parkingLot) => {
          let treeDataArr = [];
          let vemsTreeArr = vems.data ? vems.data : [];
          let parkingLotTreeArr = parkingLot.data ? parkingLot.data : [];
          treeDataArr = vemsTreeArr.concat(parkingLotTreeArr);
          self.allParkingTreeData = deepCopyObjArray(treeDataArr);
        })
      );
    },
    // 判断是否只有一个停车场
    judgeHasOneParking(treeName) {
      let self = this;
      if (Array.isArray(self.allParkingTreeData) && self.allParkingTreeData.length === 1) {
        self.mouthTicketData.baseTicketData.parkSysType = self.allParkingTreeData[0].parkSysType;
        self.selectedParkingLotStr = self.allParkingTreeData[0].name;
        self.selectedParkingLot.push({
          name: self.allParkingTreeData[0].name
        });
        $.fn.zTree.destroy(treeName);
        let treeObj = $.fn.zTree.init($('#' + treeName), self.settings, self.allParkingTreeData);
        let nodes = treeObj.getCheckedNodes(false); //获取全部节点
        self.vipTypeData.channelAuthTree = JSON.stringify(nodes);
        let childrenNodeArr = [];
        nodes.forEach(elem => {
          if (elem.parkId && elem.channelSeq) {
            childrenNodeArr.push(elem);
          }
        });
        self.selectedParkingLot[0].children = childrenNodeArr;
        let channelNode = nodes.find(elem => {
          return elem.parkId && elem.channelSeq;
        });
        self.tableData.parkItems.push({
          parkSysType: channelNode.parkSysType, 
          parkVipTypeId: '',
          parkLongId: channelNode.parkId,
          parkId: channelNode.parkUuid,
          parkName: channelNode.parkName,
          chargeGroupCode: '', //计费组编号
          optionArr: []
        });
        //查询计费组
        self.selectChargeGroupList();
      }
    },
    getList() {
      let params = $.extend({}, this.searchParams, this.otherParams);
      this.getSpecialCarTypeConfiglist(params);
    },
    getSpecialCarTypeConfiglist(aparams) {
      let self = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      params = $.extend({}, params, aparams);
      API.operation.GetSpecialCarTypeConfiglistData(params).then(
        res => {
          let data = res.data,
            list = data.rows;
          self.tbodysInfo = list;
          self.total = data.total;
        },
        err => {}
      );
    },
    getMonthTicketManageList(aparams) {
      let self = this,
        params = {
          page: this.pageNumber,
          rp: this.pageSize
        };
      params = $.extend({}, params, aparams);
      API.monthTicket.GetMonthTicketManageData(params).then(
        res => {
          let data = res.data,
            list = data.rows;
          self.tbodysInfo = list;
          self.total = data.total;
        },
        err => {}
      );
    },
    toBase64(vm) {
      $(document).on('change', '#traderSelling input', function() {
        var file = this.files[0];
        var reader = new FileReader();
        if (!/image\/\w+/.test(file.type)) {
          vm.showToast('请确保文件为图像类型', 2);
          $('#traderSelling input').val('');
          return false;
        }
        vm.mouthTicketData.baseTicketData.sellingPicName = file.name;
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          var res = e.target.result.replace('data:image/png;base64,', '');
          res = res.replace('data:image/jpg;base64,', '');
          res = res.replace('data:image/jpeg;base64,', '');
          vm.mouthTicketData.baseTicketData.sellingPic = res;
        };
      });
      $(document).on('change', '#traderSellout input', function() {
        var file = this.files[0];
        var reader = new FileReader();
        if (!/image\/\w+/.test(file.type)) {
          vm.showToast('请确保文件为图像类型', 2);
          $('#traderSellout input').val('');
          return false;
        }
        vm.mouthTicketData.baseTicketData.selloutPicName = file.name;
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          var res = e.target.result.replace('data:image/png;base64,', '');
          res = res.replace('data:image/jpg;base64,', '');
          res = res.replace('data:image/jpeg;base64,', '');
          vm.mouthTicketData.baseTicketData.selloutPic = res;
        };
      });
    },
    openCalendar() {
      this.toOpenModal('multiCalendarModal');
    },
    saveCalendar(calendar) {
      this.vipTypeData.priDateArrStr = calendar;
      this.closed('multiCalendarModal');
    },
    //创建特殊类型
    createConfig(action, rowData) {
      var self = this;
      self.modalStatus = 1;
      self.mouthTicketData.ticketModalName = '新增特殊类型';
      self.mouthTicketData.tabName = 'basicTab';
      self.initMouthData_create();
      self.judgeHasOneParking('ParkTree');
      self.toOpenModal('monthlyTicketModal');
    },
    initMouthData_create() {
      var self = this;
      self.enableParkSysType = true;
      self.showMessage = deepCopyObj(self.showMessage_);
      self.mouthTicketData.baseTicketData = {
        id: '',
        parkSysType: '',
        vipGroupType: 2,
        name: '',
        description: '',
        sellFromTo: [],
        validFromTo: [],
        validDateType: '',
        maxSellNum: '',
        financialParkId: '',
        parkJson: [],
        remark: '',
        sellingPic: '',
        selloutPic: '',
        sellingPicName: '',
        selloutPicName: '',
        renewFormerDays: 0,
        inviteCarTotal: 3,
        parkVipTypeJson: ''
      };
      self.vipTypeData = {
        id: null,
        customVipName: '',
        settlementType: 0,
        settlementAmount: null,
        isDynamicMode: 0,
        dynamicCarportNumber: null,
        isDatePrivilege: 0,
        isTimePrivilege: 0,
        privilegeTimePeriod: null,
        isChargeGroupRelated: 0,
        chargeGroupCode: null,
        vipGroupType: 0,
        dynamicFullLimit: 0,
        dynamicCarNumber: null,
        vipNearExpiredDayThreshold: 10,
        vipDeleteExpiredDayThreshold: 0,
        openVipFullLimit: 0,
        vipFullLimitValue: '',
        vipFullOpenModel: 0,
        vipRecoverTime: null,
        priTimeArr: self.today,
        priTimeArrFrom: '', //开始时间
        priTimeArrTo: '', //结束时间
        priDateArrStr: '',
        parkId: '',
        parkName: '',
        channelAuthTree: '',
        channelSeqList: []
      };
      this.picPath = {
        sellingPicPath: '',
        selloutPicPath: ''
      };
      this.picShow = {
        sellingPicShow: '',
        selloutPicShow: ''
      };
      this.tableData = {
        parkItems: []
      };
      this.entity.parkList = [];
      self.selectedParkingLot = [];
      self.selectedParkingLotStr = '';
    },
    // 编辑时初始化数据
    initMouthData_edit(rowData) {
      var self = this;
      self.initMouthData_create();
      self.enableParkSysType = false;
      self.mouthTicketData.baseTicketData = {
        id: rowData.id,
        vipGroupType: rowData.vipGroupType,
        parkSysType: rowData.parkSysType,
        name: rowData.name,
        description: rowData.description,
        financialParkId: rowData.financialParkId
      };
      self.entity.parkList = [];
      self.tableData.parkItems = [];
      var rowDataParkList = [];
      if (rowData.vipGroupType == 2) {
        //黑名单
        rowDataParkList = rowData.blacklistConfigParkList;
      } else if (rowData.vipGroupType == 1) {
        //访客
        rowDataParkList = rowData.visitorlistConfigParkList;
      } else {
        //预定
        rowDataParkList = rowData.bookingConfigParkList;
      }
      for (var i = 0; i < rowDataParkList.length; i++) {
        rowDataParkList[i].parkSysType = rowData.parkSysType
        self.tableData.parkItems.push(rowDataParkList[i]);
        self.entity.parkList.push(rowDataParkList[i]);
      }
      self.showMessage = JSON.parse(rowData.showMessage);
      copyObjBySelf(self.vipTypeData, rowData.parkVipType);
      self.vipTypeData.channelAuthTree = JSON.stringify(rowData.channelArr);
      if (
        rowData.parkVipType.isTimePrivilege == 1 &&
        null != rowData.parkVipType.privilegeTimePeriod &&
        '' != rowData.parkVipType.privilegeTimePeriod
      ) {
        self.vipTypeData.priTimeArrFrom = new Date(
          moment().format('YYYY-MM-DD ' + rowData.parkVipType.privilegeTimePeriod.split('-')[0] + ':00')
        );
        self.vipTypeData.priTimeArrTo = new Date(
          moment().format('YYYY-MM-DD ' + rowData.parkVipType.privilegeTimePeriod.split('-')[1] + ':59')
        );
      }

      let channelArr = JSON.parse(JSON.stringify(rowData.channelArr));
      let channelArrTmp = [];
      let selectedParkingLotStrTmp = [];
      for (let i = 0; i < channelArr.length; i++) {
        let obj = channelArr[i];
        if (obj.parkId) {
          //通道节点
          if (channelArrTmp.hasOwnProperty(obj.parkName)) {
            channelArrTmp[obj.parkName].push(obj);
          } else {
            channelArrTmp[obj.parkName] = [];
            channelArrTmp[obj.parkName].push(obj);
          }
        }
      }
      for (let key in channelArrTmp) {
        if (channelArrTmp.hasOwnProperty(key)) {
          selectedParkingLotStrTmp.push(key);
          self.selectedParkingLot.push({
            parkId: channelArrTmp[key][0].parkId,
            name: channelArrTmp[key][0].parkName,
            open: true,
            children: channelArrTmp[key]
          });
        }
      }
      self.selectedParkingLotStr = selectedParkingLotStrTmp.join('/');
      //查询计费组
      if(rowData.parkSysType===1){
        self.selectChargeGroupList();
      }
    },
    // 车辆分类-新增or编辑-tab切换
    selectMonthTicketInfoTab(tabName) {
      this.mouthTicketData.tabName = tabName;
    },
    // 月票类型-查看-tab切换
    selectMonthTicketCheckInfoTab(tabName) {
      this.specialCarTypeObj.tabName = tabName;
    },
    // 编辑月票是调用函数
    editConfig(ticketId, title) {
      var self = this;
      var params = {};
      params.id = ticketId;
      API.operation.GetSpecialCarTypeConfigDetail(params).then(
        res => {
          self.createTicket(title, res.data);
        },
        err => {}
      );
    },
    // 创建月票时入口
    createTicket(modalName, rowData) {
      var self = this;
      this.$set(this.mouthTicketData, 'ticketModalName', modalName);
      // 判断是创建还是编辑
      if (modalName.indexOf('新增') > -1) {
        self.mouthTicketData.tabName = 'basicTab';
        self.initMouthData_create();
      } else {
        self.initMouthData_edit(rowData);
      }
      self.toOpenModal('monthlyTicketModal');
    },
    // 查看特殊车辆类型
    async checkSpecialCarType(rowData) {
      let self = this;
      self.clearSpecialCarTypeObj(); //清空查看月票对象
      self.modalStatus = 5;
      let params = {
        id: rowData.id
      };
      await self.fetchSpecialCarTypeData(params);
      self.toOpenModal('specialCarTypeCheck');
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    // 清空查看特殊车辆类型对象
    clearSpecialCarTypeObj() {
      this.specialCarTypeObj = {
        dialogVisible: false,
        tabName: '',
        basicData: {
          channelArr: [], //所选通道
          name: '', //类型名称
          vipGroupTypeStr: '', //特殊车辆类型
          description: '' //简介
        },
        superiorData: {
          moreCarMoreSeat: '', //是否支持多车多位
          autoSwitchVip: '', //是否支持场内切换
          dynamicFullLimit: '', //是否支持内场多位多车满位到剩余

          openVipFullLimit: '', //是否支持满位控制
          vipFullLimitValue: '', //最多可进多少辆车
          vipFullOpenModel: '', //满位放行模式

          isDatePrivilege: '', //是否按日期
          priDateArrStr: '', //已选择的日期

          isTimePrivilege: '', //是否按时间段
          timeSlot: '', //时间段

          iScharging: '' //是否计费
        }
      };
    },
    // 获取特殊车辆类型数据
    fetchSpecialCarTypeData(params) {
      let self = this;
      return API.fetchGet('/park/specialCarTypeConfig/detail.do', params).then(res => {
        if (res.data) {
          let data = res.data;
          self.tableData.parkItems = [];
          self.specialCarTypeObj.tabName = 'basicTab';
          self.specialCarTypeObj.basicData.name = data.name; //类型名称
          self.specialCarTypeObj.basicData.vipGroupTypeStr =
            data.vipGroupType == 1 ? '访客' : data.vipGroupType == 2 ? '黑名单' : '预定'; // 特殊车辆类型
          self.specialCarTypeObj.basicData.description = data.description;
          self.tableData.parkItems = [];
          let rowDataParkList = [];
          if (data.vipGroupType == 2) {
            //黑名单
            rowDataParkList = data.blacklistConfigParkList;
          } else if (data.vipGroupType == 1) {
            //访客
            rowDataParkList = data.visitorlistConfigParkList;
          } else {
            //预定
            rowDataParkList = data.bookingConfigParkList;
          }
          for (var i = 0; i < rowDataParkList.length; i++) {
            rowDataParkList[i].parkSysType = data.parkSysType
            self.tableData.parkItems.push(rowDataParkList[i]);
          }
          // 查询计费组
          if(data.parkSysType===1){
            self.selectChargeGroupList();
          }
          if (data.channelArr) {
            let arr = {};
            for (let i = 0; i < data.channelArr.length; i++) {
              let node = data.channelArr[i];
              if (node.channelSeq && node.parkId) {
                //通道节点
                let parkName = node.parkName;
                let channelName = node.name;
                if (arr.hasOwnProperty(node.parkName)) {
                  arr[parkName].push(channelName);
                } else {
                  arr[parkName] = [];
                  arr[parkName].push(channelName);
                }
              }
            }
            for (let key in arr) {
              if (arr.hasOwnProperty(key)) {
                let obj = {
                  parkName: key,
                  channelName: arr[key].join('/')
                };
                self.specialCarTypeObj.basicData.channelArr.push(obj);
              }
            }
          }

          // 高级配置
          let parkVipType = data.parkVipType;
          self.specialCarTypeObj.superiorData.moreCarMoreSeat = parkVipType.isDynamicMode == 1 ? '支持' : '不支持'; //多位多车
          self.specialCarTypeObj.superiorData.autoSwitchVip = parkVipType.autoSwitchVip == 1 ? 1 : 0; //内场切换
          self.specialCarTypeObj.superiorData.dynamicFullLimit = parkVipType.dynamicFullLimit == 1 ? 1 : 0;
          self.specialCarTypeObj.superiorData.openVipFullLimit = parkVipType.openVipFullLimit == 1 ? '支持' : '不支持'; //满位控制
          self.specialCarTypeObj.superiorData.vipFullLimitValue = parkVipType.vipFullLimitValue
            ? parkVipType.vipFullLimitValue
            : 0; //最多可进
          self.specialCarTypeObj.superiorData.vipFullOpenModel = parkVipType.vipFullOpenModel; //满位放行模式
          self.specialCarTypeObj.superiorData.isDatePrivilege = parkVipType.isDatePrivilege == 1 ? '支持' : '不支持'; //按日期
          self.specialCarTypeObj.superiorData.priDateArrStr = parkVipType.priDateArrStr; //日期控件数据
          self.specialCarTypeObj.superiorData.isTimePrivilege = parkVipType.isTimePrivilege == 1 ? '支持' : '不支持'; //是否时间段
          self.specialCarTypeObj.superiorData.timeSlot = parkVipType.privilegeTimePeriod; //时间段
          self.specialCarTypeObj.superiorData.iScharging = parkVipType.isChargeGroupRelated == 1 ? '是' : '否'; //是否计费
        }
      });
    },
    // 列表查看支持停车场
    supportParkShowModal(row) {
      var _this = this;
      _this.toOpenModal('selectParkModal');
      _this.initChannelTree('ParkTree', row);
    },
    // 同步详情弹框
    synchronismDetialModal(row) {
      var self = this;
      self.configId = row.id;
      self.supportParkList = [];
      API.operation
        .FindSendStatusList({
          configId: row.id
        })
        .then(
          res => {
            var data = res;
            self.supportParkList = data.data;
          },
          err => {}
        );
      this.toOpenModal('synchronismDetialModal');
    },
    resend(row) {
      var self = this;
      API.operation
        .resendVipTypeToPark({
          sendStatusId: row.id
        })
        .then(
          res => {
            //重新加载同步详情
            API.operation
              .FindSendStatusList({
                configId: self.configId
              })
              .then(
                res2 => {
                  var data = res2;
                  self.supportParkList = data.data;
                },
                err2 => {}
              );
          },
          err => {}
        );
    },
    openSelectParkModal() {
      var _this = this;
      _this.toOpenModal('selectParkModal');
      setTimeout(_this.initChannelTree, 500, 'ParkTree');
    },
    initParkTree(treeId) {
      var _this = this;
      API.monthTicket.getParkTree({}).then(
        res => {
          var data = res;
          if (data != null) {
            var nodes = data.data;
            var jsonStr = JSON.stringify(nodes);

            jsonStr = jsonStr.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true, "nocheck":true,');
            nodes = JSON.parse(jsonStr);
            var settings = {
              check: {
                enable: true,
                chkStyle: 'checkbox',
                radioType: 'all'
              },
              view: {
                showIcon: false,
                showLine: false
              },
              callback: {
                onClick: function(event, treeId, treeNode) {
                  var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
                  treeObj.checkNode(treeNode, true, false);
                  if (treeNode.isArea) {
                    return;
                  }
                }
              }
            };
            $.fn.zTree.destroy('ParkTree');

            var treeObj = $.fn.zTree.init($('#ParkTree'), settings, nodes);
            for (var i = 0; i < _this.entity.parkList.length; i++) {
              var node = treeObj.getNodeByParam('value', _this.entity.parkList[i]);
              if (node) {
                if (node.getParentNode() && !node.getParentNode().open) {
                  treeObj.expandNode(node.getParentNode(), true, true, true);
                }
                treeObj.checkNode(node, true, true);
              }
            }
            treeObj.expandAll(true);
          } else {
            _this.showToast('暂时没有停车场可选', 2, 3000);
          }
        },
        err => {}
      );
    },
    searchItems(treeName) {
      var self = this;
      var treeObj = $.fn.zTree.getZTreeObj(treeName);
      var nodes = treeObj.getNodesByParamFuzzy('name', self.itemsKeyName, null);
      treeObj.cancelSelectedNode();
      nodes.forEach(function(node) {
        treeObj.selectNode(node, true, false);
      }, this);
    },
    selectAllItems(treeName) {
      var self = this;
      var treeObj = $.fn.zTree.getZTreeObj(treeName);
      if (self.selectAllItemsStatus == '0') {
        treeObj.checkAllNodes(true);
      } else {
        treeObj.checkAllNodes(false);
      }
      self.setItemNums(treeName);
    },
    setItemNums(treeName) {
      var self = this;
      var treeObj = $.fn.zTree.getZTreeObj(treeName);
      var nodes = treeObj.getCheckedNodes(true);
      var itemsNum_ = 0;
      nodes.forEach(function(node) {
        if (!node.isParent && node.channelSeq) {
          itemsNum_++;
        }
      }, this);
      self.itemsNum = itemsNum_;
    },
    async initChannelTree(treeName, rowParam) {
      let self = this;
      let params, nodes;
      if (rowParam) {
        self.selectParkModalStatus = 0; //停车场树选择框-确认按钮
        params = {
          id: rowParam.id
        };
        nodes = await self.fetchConfigParkChannels(params);
      } else {
        self.selectParkModalStatus = 1; //停车场树选择框-确认按钮
        nodes = deepCopyObjArray(self.allParkingTreeData);
      }
      $.fn.zTree.destroy(treeName);
      this.isShowTree = true;
      if (!nodes || nodes.length == 0) {
        this.isShowTree = false;
        return;
      }
      let treeObj = $.fn.zTree.init($('#ParkTree'), self.settings, []);
      //每次都从数据库获取通道的信息，然后从已保存的channelAuthTree中checked
      if (self.vipTypeData.channelAuthTree && self.vipTypeData.channelAuthTree != '') {
        var selectTreeNodes = JSON.parse(self.vipTypeData.channelAuthTree); //已选的通道节点
        var treeNodes = nodes; //全部节点
        var simpleNodesArray = treeObj.transformToArray(treeNodes); //将全部节点转为普通对象
        for (var i = 0; i < simpleNodesArray.length; i++) {
          var simpleNode = simpleNodesArray[i];
          for (var j = 0; j < selectTreeNodes.length; j++) {
            var treeNode = selectTreeNodes[j];
            if (
              simpleNode.parkId &&
              simpleNode.channelSeq &&
              treeNode.areaId == simpleNode.areaId &&
              treeNode.parkId == simpleNode.parkId &&
              treeNode.channelSeq == simpleNode.channelSeq
            ) {
              simpleNode.checked = true;
              break;
            }
          }
        }
        nodes = treeNodes;
      }
      treeObj.addNodes(null, 0, nodes);

      //勾选父节点的操作
      var temp_checkNodes = treeObj.getCheckedNodes();
      temp_checkNodes.forEach(function(t) {
        if (!t.hasChildren) {
          treeObj.checkNode(t, true, true);
        }
      }, this);

      treeObj.expandAll(true);
    },
    // 获取已选择的停车场通道数据
    fetchConfigParkChannels(params) {
      let self = this;
      return new Promise((resolve, reject) => {
        API.fetchPost('/park/specialCarTypeConfig/getConfigParkChannels.do', params).then(
          res => {
            resolve(res.data);
          },
          err => {}
        );
      });
    },
    // modal弹框--选择停车场时确认时调用函数
    selectParkSure() {
      var self = this,
        nodes = [];
      var params = deepCopyObj(self.vipTypeData);
      var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
      nodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点

      //通道信息json
      params.channelAuthTree = JSON.stringify(nodes);
      self.vipTypeData.channelAuthTree = JSON.stringify(nodes);
      let parkList = new Array();
      let selectedParkListTmp = [];

      for (var i = 0; i < nodes.length; i++) {
        //过滤重复的停车场，只有通道才有parkId值
        var node = nodes[i];
        if (node.parkId) {
          parkList[node.parkId] = node;
          // 以停车场为单位进行组合
          if (selectedParkListTmp.hasOwnProperty(node.parkName)) {
            selectedParkListTmp[node.parkName].push(node);
          } else {
            selectedParkListTmp[node.parkName] = [];
            selectedParkListTmp[node.parkName].push(node);
          }
        }
      }
      if (parkList.length <= 0) {
        self.showToast('请选择至少一个通道', 0);
        return;
      }
      self.mouthTicketData.baseTicketData.parkSysType = nodes[0].parkSysType;
      // 初始化表格显示数据以及提交的表格参数
      self.tableData = {
        parkItems: []
      };
      self.selectedParkingLot = [];
      self.selectedParkingLotStr = '';
      self.entity.parkList = [];
      self.mouthTicketData.baseTicketData.parkJson = [];
      let itemobjArr = [];
      let selectedParkingLotStrArr = [];
      for (let key in parkList) {
        if (parkList.hasOwnProperty(key)) {
          itemobjArr.push({
            parkSysType: parkList[key].parkSysType, 
            parkVipTypeId: '',
            parkLongId: parkList[key].parkId,
            parkId: parkList[key].parkUuid,
            parkName: parkList[key].parkName,
            chargeGroupCode: parkList[key].chargeGroupCode,
            optionArr: []
          });
          self.entity.parkList.push(parkList[key]);
          selectedParkingLotStrArr.push(parkList[key].parkName);
        }
      }
      for (let key in selectedParkListTmp) {
        if (selectedParkListTmp.hasOwnProperty(key)) {
          self.selectedParkingLot.push({
            parkId: selectedParkListTmp[key][0].parkId,
            name: selectedParkListTmp[key][0].parkName,
            open: true,
            children: selectedParkListTmp[key]
          });
        }
      }
      self.selectedParkingLotStr = selectedParkingLotStrArr.join('/');
      self.closed('selectParkModal');
      self.tableData.parkItems = itemobjArr;
      //查询计费组
      if(self.mouthTicketData.baseTicketData.parkSysType===1){
        self.selectChargeGroupList();
      }
    },
    // 计费组
    selectChargeGroupList() {
      var self = this;
      if (self.tableData.parkItems) {
        let parkIdList = [];
        self.tableData.parkItems.forEach(function(item_) {
          parkIdList.push(item_.parkId);
        }, this);

        API.fetchGet('/park/specialCarTypeConfig/selectChargeGroupList2.do',{
            parkIdList: parkIdList.join(',')
          }).then(
            res2 => {
              var data = res2.data;
              var parkItems = self.tableData.parkItems;
              parkItems.forEach(function(parkItem) {
                parkItem.optionArr = [];
                let defaultOption = '';
                for (let key in data) {
                  if (key == parkItem.parkId) {
                    let tmpArr = data[key];
                    for (let i = 0; i < tmpArr.length; i++) {
                      tmpArr[i].chargeTypeSeq += '';
                      parkItem.optionArr.push(tmpArr[i]);
                      if (
                        parkItem.chargeGroupCode !== 0 &&
                        parkItem.chargeGroupCode !== '0' &&
                        !parkItem.chargeGroupCode
                      ) {
                        defaultOption = tmpArr[i].chargeTypeSeq == 0 ? tmpArr[i].chargeTypeSeq : defaultOption;
                      }
                    }
                    if (
                      parkItem.chargeGroupCode !== 0 &&
                      parkItem.chargeGroupCode !== '0' &&
                      !parkItem.chargeGroupCode
                    ) {
                      parkItem.chargeGroupCode = defaultOption;
                    }
                  }
                }
              }, this);
              this.chargeGroupRender = false;
              this.$nextTick(() => {
                this.chargeGroupRender = true;
              });
            },
            err2 => {}
          );
      }
    },
    // 删除停车场时调用的函数
    delectSelectParkItem(index, rowData) {
      var _this = this;
      _this.tableData.parkItems.splice(index, 1);
      _this.entity.parkList.splice(index, 1);
      var tempTree = JSON.parse(_this.vipTypeData.channelAuthTree);
      var tempTree_ = [];
      var tIdList = [];
      for (var i = 0; i < tempTree.length; i++) {
        var tt = tempTree[i];
        if (tt.level == 0 && tt.name == rowData.parkName) {
          //需要删除的停车场
          //还需要递归删除区域和通道的项
          _this.recursiveItem(tt, tt.tId, tIdList);
        }
      }
      //过滤
      var tIdListStr = tIdList.join(',');
      for (var i = 0; i < tempTree.length; i++) {
        var tt = tempTree[i];
        if (tIdListStr.indexOf(tt.tId) >= 0) {
        } else {
          tempTree_.push(tt);
        }
      }
      var tempTreeStr = JSON.stringify(tempTree_);
      _this.vipTypeData.channelAuthTree = tempTreeStr;
    },

    recursiveItem(item, tId, tIdList) {
      var self = this;
      tIdList.push(tId);
      if (item.hasChildren && item.childrenList && item.childrenList.length > 0) {
        var childrenList = item.childrenList;
        for (var i = 0; i < childrenList.length; i++) {
          var child = childrenList[i];
          self.recursiveItem(child, child.tId, tIdList);
        }
      }
    },

    submitForm(formName) {
      var self = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          self.saveTicket(formName);
        } else {
          return false;
        }
      });
    },
    // 编辑(2:基础信息;3:高级配置)
    modifyConfig(ticket, type) {
      let title = '';
      this.modalStatus = type;
      if (type == 3) {
        this.mouthTicketData.tabName = 'higherTab';
        title = '高级配置';
      } else {
        this.mouthTicketData.tabName = 'basicTab';
        title = '基础配置';
      }
      this.entity.id = ticket.id;
      this.editConfig(ticket.id, title);
    },

    //value为13位的时间戳
    formatTime(value) {
      function addzero(m) {
        return m < 10 ? '0' + m : m;
      }
      var time = new Date(parseInt(value));
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      var shi = time.getHours();
      var fen = time.getMinutes();
      var miao = time.getSeconds();
      if (value) {
        return y + '-' + addzero(m) + '-' + addzero(d) + ' ' + addzero(shi) + ':' + addzero(fen) + ':' + addzero(miao);
      }
    },
    // 保存月票时调用函数
    saveTicket(formName) {
      var self = this;
      if(self.vipTypeData.isChargeGroupRelated){ //计费
        if(Array.isArray(self.tableData.parkItems) && self.tableData.parkItems[0].parkSysType===0){
          for(let i = 0; i<self.tableData.parkItems.length; i++){
            let elem = self.tableData.parkItems[i]
            if(!elem.chargeGroupCode){
              self.showToast('请填写计费组编号',0,1500);
              return;
            }
            if(!/^[0-9]+$/.test(elem.chargeGroupCode)){
              self.showToast('计费组编号只能输入数字',0,1500);
              return;
            }
          }
        }
      }
      var params = deepCopyObj(self.mouthTicketData.baseTicketData);

      params['parkJson'] = JSON.stringify(self.tableData.parkItems);
      var vipTypeData_ = deepCopyObj(self.vipTypeData);

      //收费组
      if (self.vipTypeData.isChargeGroupRelated == 0) {
        vipTypeData_.chargeGroupCode = null;
      }

      // 按日期
      if (self.vipTypeData.isDatePrivilege && !self.vipTypeData.priDateArrStr) {
        self.showToast('请选择区分日期', 0);
        return;
      }

      //区分时间段
      if (
        self.vipTypeData.isTimePrivilege &&
        self.vipTypeData.priTimeArrFrom instanceof Date &&
        self.vipTypeData.priTimeArrTo instanceof Date
      ) {
        vipTypeData_.privilegeTimePeriod =
          self.vipTypeData.priTimeArrFrom.Format('hh:mm') + '-' + self.vipTypeData.priTimeArrTo.Format('hh:mm');
      } else {
        vipTypeData_.privilegeTimePeriod = '';
      }

      if (self.vipTypeData.isTimePrivilege && vipTypeData_.privilegeTimePeriod == '') {
        self.showToast('请选择区分时间段范围', 0);
        return;
      }

      params.parkVipTypeJson = JSON.stringify(vipTypeData_);
      params['showMessage'] = JSON.stringify(self.showMessage);

      if (self.mouthTicketData.baseTicketData.id) {
        let editUrl = '/park/specialCarTypeConfig/edit.do'; //基本信息-编辑接口
        if (self.modalStatus == 3) {
          editUrl = '/park/specialCarTypeConfig/editAdvancedConfig.do'; //高级配置-编辑接口
        }
        if (self.modalStatus == 4) {
          editUrl = '/park/specialCarTypeConfig/saveShowMessage.do'; //显示及语音-编辑接口
        }
        API.fetchPost(editUrl, params).then(
          res => {
            var data = res;
            if (data.status == 1) {
              self.showToast('修改成功', 1);
              self.getList();
              if (formName && formName == 'textVoiceForm') {
                self.dialogVisibleOfShowMessage = false;
              } else {
                self.closed('monthlyTicketModal');
              }
            } else {
              self.showToast(data.message, 2);
            }
          },
          err => {}
        );
      } else {
        API.operation.specialCarTypeConfigAdd(params).then(
          res => {
            var data = res;
            if (data.status == 1) {
              self.showToast('创建成功', 1);
              self.getList();
              if (formName && formName == 'textVoiceForm') {
                self.dialogVisibleOfShowMessage = false;
              } else {
                self.closed('monthlyTicketModal');
              }
            } else {
              self.showToast(data.message, 2);
            }
          },
          err => {}
        );
      }
    },
    delTicket(ticket) {
      var self = this;
      if (ticket.sellNum > 0) {
        return;
      }
      var params = {
        configId: ticket.id
      };
      self.showDialog('确认删除该特殊车辆类型?', '', function() {
        API.operation.DeleteSpecialCarTypeConfig(params).then(
          res => {
            //start
            var data = res;
            self.showToast('删除成功', 1);
            self.getList();
            //end
          },
          err => {}
        );
      });
    },
    updateStatusTicket(ticket, status) {
      var self = this;
      var params = {
        monthTicketConfigId: ticket.id,
        monthTicketStatus: status
      };

      var type = status == 'VALID' ? '上架' : '下架';
      self.showDialog('确认' + type + '该月票?', '', function() {
        API.monthTicket.manageUpdateStatus(params).then(
          res => {
            //start
            var data = res;
            self.showToast('操作成功', 1);
            self.getList();
            //end
          },
          err => {}
        );
      });
    },
    // 删除停车场时调用的函数
    delectSelectParkItem(index, parkId) {
      var _this = this;
      _this.tableData.parkItems.splice(index, 1);
      if (_this.mouthTicketData.baseTicketData.financialParkId == parkId) {
        _this.mouthTicketData.baseTicketData.financialParkId = null;
      }
    }
  },
  filters: {
    vipFullOpenModel: function(val){
      switch (val) {
        case 0:
          return '系统有空位自动放行，无空位手动放行按VIP计费';
        case 1:
          return '系统有空位自动放行，无空位手动放行按临时车计费';
        case 2:
          return '系统无空位自动放行，按临时车计费';
        default:
          break;
      }
    },
    ticketType: function(val) {
      switch (val) {
        case 'OUTTER':
          return '对外月票';
        case 'INNER':
          return '对内月票';
        default:
          break;
      }
    },
    ticketStatus: function(val) {
      switch (val) {
        case 'INVALID':
          return '未上架';
        case 'VALID':
          return '已上架';
        case 'EXPIRED':
          return '已过期';
        default:
          break;
      }
    },
    renewMethod: function(val) {
      switch (val) {
        case 'NATURAL_MONTH':
          return '自然月';
        case 'CUSTOM':
          return '自定义';
        default:
          break;
      }
    },
    vipGroupTypeStr: function(val) {
      switch (val) {
        case 1:
          return '访客';
        case 2:
          return '黑名单';
        case 3:
          return '预定';
        default:
          break;
      }
    }
  }
};
